﻿namespace Smart.Utils.ExcelDataReader.Core
{
    using System;
    using System.IO;

    internal class XlsStream
    {
        protected XlsFat m_fat;
        protected Stream m_file;
        protected XlsHeader m_hdr;
        protected uint m_startSector;

        public XlsStream(XlsHeader hdr, uint startSector)
        {
            this.m_file = hdr.FileStream;
            this.m_fat = hdr.FAT;
            this.m_hdr = hdr;
            this.m_startSector = startSector;
        }

        public byte[] ReadStream()
        {
            uint startSector = this.m_startSector;
            uint num2 = 0;
            int sectorSize = this.m_hdr.SectorSize;
            byte[] buffer = new byte[sectorSize];
            using (MemoryStream stream = new MemoryStream(sectorSize * 8))
            {
                lock (this.m_file)
                {
                    do
                    {
                        if ((num2 == 0) || ((startSector - num2) != 1))
                        {
                            this.m_file.Seek((startSector + 1) * sectorSize, SeekOrigin.Begin);
                        }
                        num2 = startSector;
                        this.m_file.Read(buffer, 0, sectorSize);
                        stream.Write(buffer, 0, sectorSize);
                    }
                    while ((startSector = this.m_fat.GetNextSector(startSector)) != 0xfffffffe);
                }
                byte[] buffer2 = stream.ToArray();
                stream.Close();
                return buffer2;
            }
        }

        public uint BaseOffset
        {
            get
            {
                return (uint) ((this.m_startSector + 1) * this.m_hdr.SectorSize);
            }
        }

        public uint BaseSector
        {
            get
            {
                return this.m_startSector;
            }
        }
    }
}

